package cn.wolfcode.rocketmq._02_send_way;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

public class Producer {
    public static void main(String[] args) throws Exception {
        //1.创建出来一个生产者对象
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("producer-demo");
        //发送消息的超时时间
        defaultMQProducer.setSendMsgTimeout(10000);
        //2.绑定nameser的地址
        defaultMQProducer.setNamesrvAddr("localhost:9876");
        final CountDownLatch countDownLatch = new CountDownLatch(100);
        //3.启动生产者
        defaultMQProducer.start();
        //4.创建一个消息对象,把要发送的消息放到消息对象中

        for (int i = 1; i <100; i++) {
            Message message = new Message("02-send-way","nihaoya".getBytes());
            //5.使用生产者发送消息
            defaultMQProducer.send(message, new SendCallback() {
                public void onSuccess(SendResult sendResult) {
                    System.out.println("发送成功");
                    countDownLatch.countDown();
                }

                public void onException(Throwable throwable) {
                    System.out.println("发送失败");
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        //6.关闭资源
        defaultMQProducer.shutdown();
    }

}
